import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/user/login.vue'
import home from '../views/home/home.vue'
import movie from '../views/movie/movie.vue'
import qa from '../views/qa/qa.vue'
import user from '../views/user/user.vue'
import notfound from '../views/notfound/notfound.vue'
import edit from '../views/user/edit.vue'
import student from '../views/user/student.vue'
import { getToken } from '@/utils/token.js'
import article from '../views/home/article.vue'
import search from '../views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
// 事件格式转化
import moment from 'moment'
moment.locale('zh-cn')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/home',
    name: 'home',
    component: home,
    // 路由元信息
    meta: { showTab: true }
  },
  {
    path: '/movie',
    name: 'movie',
    component: movie,
    meta: { showTab: true }
  },
  {
    path: '/qa',
    name: 'qa',
    component: qa,
    meta: { showTab: true }
  },
  {
    path: '/user',
    name: 'user',
    component: user,
    meta: { showTab: true, isLogin: true }
  },
  {
    path: '/notfound',
    name: 'notfound',
    component: notfound
  },
  {
    path: '/edit',
    name: 'edit',
    component: edit
  },
  {
    path: '/student',
    name: 'student',
    component: student
  },
  {
    path: '/article',
    name: 'myarticle',
    component: article
  },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    component: searchResult
  },
  // // 路由重定向：场景1(跳转到首页。例如，京东)
  // {
  //   path: '/',
  //   redirect: '/home'
  // }
  // 路由重定向：场景1(跳转到404页面。例如，天猫)
  // haxi值乱输入，用*表示path（万能路由）
  {
    path: '*',
    redirect: '/notfound'
  }
]

// 1解决router.push()报错
// 进阶思维
// 1.1 覆盖原有的push方法：用临时变量保存起来
let originPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onResolve, onReject) {
  // 1.3 除了catch方法改变以后，push方法的其他一切正常
  if (onResolve || onReject) {
    return originPush.call(this, location, onResolve, onReject)
  } else {
    // 1.2 改变catch方法的执行代码段
    return originPush.call(this, location).catch(err => {})
  }
}

const router = new VueRouter({
  routes
})

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // ...
  // to:去往用户页面才需要判断是否正常跳转。因为只有登陆了才能到用户页面
  // 判断是否登录：有无token。退出了登录获取token为undefined，取反=true，条件成立
  if (to.meta.isLogin && !getToken()) {
    next({ path: '/login' })
  } else {
    // next 表示正常跳转
    next()
  }
})

// 全局过滤器
Vue.filter('showTime', value => {
  return moment(value).fromNow()
})

export default router
